<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Traits\LogsActivity;

class Role extends \Spatie\Permission\Models\Role
{
    use LogsActivity;

    protected static $logOnlyDirty = true;

    protected static $logAttributes = ['*'];

    protected $guarded = [];

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
    ];

    /**
     * 状态: 正常
     */
    const STATUS_NORMAL = 1;

    /**
     * 状态: 禁用
     */
    const STATUS_DISABLE = 2;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('status', function (Builder $builder) {
            $builder->where('status', self::STATUS_NORMAL);
        });
    }

    /**
     * 允许前端传长度
     * @return int
     */
    public function getPerPage(): int
    {
        return (int) (app('request')->input('per_page', null) ?: parent::getPerPage());
    }

    /**
     * 自定义操作日志 说明
     * @param $eventName
     * @return string
     */
    public function getDescriptionForEvent(string $eventName): string
    {
        if (in_array($eventName, ['created', 'updated', 'deleted'])) {
            switch ($eventName) {
                case 'created':
                    return '创建角色:' . $this->name;
                case 'updated':
                    $fieldMap = [
                        'name' => [
                            'title' => '角色名称',
                        ],
                        'remark' => [
                            'title' => '备注',
                        ],
                        'status' => [
                            'title' => '状态',
                            'casts' => [
                                Role::STATUS_NORMAL => '启用',
                                Role::STATUS_DISABLE => '禁用',
                            ]
                        ]
                    ];
                    $changes = [];
                    foreach ($this->getChanges() as $field => $change) {
                        if (!isset($fieldMap[$field])) {
                            continue;
                        }

                        $changes[] = $fieldMap[$field]['title'] . '变更为' . (isset($fieldMap[$field]['casts']) ? $fieldMap[$field]['casts'][$change] : $change);
                    }
                    return '编辑角色:' . $this->getOriginal('name') . ',变更内容:' . implode(',', $changes);
                case 'deleted':
                    return '删除角色:' . $this->name;
            }
        }

        return $eventName;
    }

    /**
     * 操作日志 custom 操作
     * @param ActivityLog $activity
     * @param string $eventName
     */
    public function tapActivity(ActivityLog $activity, string $eventName)
    {
        $activity->properties = $activity->properties->put('ip', app('request')->ip());
    }
}
